/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//Simbolo  String
//Prefijo o sufijo

package bsc.war.form;

import bsc.ejb.metadata.Framework;
import bsc.ejb.metadata.Unit;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author luisZavaleta
 */
public class NewUnit extends AbstractController{

     @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
             HttpServletResponse response) throws Exception {
         
         ModelAndView mav = new ModelAndView("renderXml");

         try {

             boolean edit = false;
             Long unitId = -1L;

             if (NumberUtils.isDigits(request.getParameter("id"))) {
                 Long id = Long.valueOf(request.getParameter("id"));
                 if (id >= 0) {
                     edit = true;
                     unitId = id;
                 }
             }

             HttpSession session = request.getSession();

             DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
             Unit unit = edit ? delegate.findUnit(unitId) : (Unit)Factory.getBean("Unit");


             Framework framework = null;
             if (session.getAttribute("frameworkId") instanceof Long) {

                 Long frameworkId = (Long) session.getAttribute("frameworkId");
                 framework = (Framework) Factory.getBean("Framework");
                 framework = delegate.findFramework(Long.valueOf(frameworkId));

             } else {
                 throw new Exception("no hay frameworkId");
             }

             unit.setName(request.getParameter("name"));
             unit.setDescription(request.getParameter("description"));
             unit.setFramework(framework);

             if (edit) {
                 delegate.updateUnit(unit);
             } else {
                 delegate.createUnit(unit);
             }

             mav.addObject("id", unit.getIdUnit());
         } catch (Exception e) {
             e.printStackTrace();
         }

         return mav;
    }

}
